<template>
  <div>
    <a-row style="margin-bottom: 20px;">
      <a-col :span="24">
        <a-button type="primary" style="margin-top:12px" @click="uploadBtnClkFn">
          上传
        </a-button>
      </a-col>
    </a-row>

    <!-- upload-modal -->
    <a-modal title="上传图片" :visible="modalVisible" centered :confirm-loading="confirmLoading" @ok="modalHandleOk" @cancel="modalHandleCancel">
      <a-form-model :model="modalForm" :label-col="labelCol" :wrapper-col="wrapperCol" ref="uploadModalDom" :rules="uploadFormRules">
        <a-form-model-item label="上传附件" prop="file">
          <a-upload ref="uploadDom" :multiple="false" :action="get_OSS_config" :file-list="fileListOwn" :customRequest="uploadHandleChange" @change="handleChange1">
            <a-button>
              上传图片
            </a-button>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item label="附件类型" prop="type">
          <a-select v-model="modalForm.type" placeholder="请选择附件类型" @change="selectOnchange" :getPopupContainer="(triggerNode) => triggerNode.parentNode">
            <a-select-option v-for="(item, index) in attachType" :key="index" :value="item.key">
              {{item.val}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 图片展示 -->
    <a-upload class="img_upload_div" list-type="picture-card" :file-list="fileList" @preview="handlePreview" @change="handleChange" :remove="removeFn" :text="fileList.name"></a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import datas from '@/utils/data'
import { upLoadAliyun } from "@/utils/util"
import { attachmentGetUserIdApi } from '@/services/employeeManage'
import { attachmentAddOrUpdateflowersApi, attachmentDelByIdApi } from '@/services/employeeDetail'
import { get_OSS_config } from '@/services/api'

function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default {
  name: "tabs3",
  created () {
    this.getData()
  },
  data () {
    return {
      previewVisible: false,
      previewImage: '',
      fileListOwn: [],
      fileList: [],
      modalVisible: false,
      confirmLoading: false,
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      modalForm: {
        type: '',
        file: ''
      },
      attachType: datas.attachType,
      get_OSS_config: get_OSS_config,
      imgOssPath: '',
      uploadFormRules: {
        file: [{ required: true, message: "请上传图片", trigger: "change" }],
        type: [{ required: true, message: '请选择附件类型', trigger: 'change' }],
      },
    }
  },
  methods: {
    getData () {
      let userId = this.$Storage.get('employDetail_userId')

      let params = {
        userId
      }
      attachmentGetUserIdApi(params).then(res => {
        let { code, data, msg } = res.data

        if (code == 200) {
          let _arr = []
          if (data) {
            data.forEach((item) => {
              let _obj = {}
              _obj.uid = item.id
              _obj.url = item.attachUrl
              _obj.attachType = item.attachType
              _obj.name = item.name
              if (item.attachUrl) {
                _obj.status = 'done'
              } else {
                _obj.status = 'error'
              }
              _arr.push(_obj)

              datas.attachType.forEach(k => {
                if (k.val == item.name) {
                  k.disable = true
                }
              })

            })

            this.fileList = _arr
            this.attachType = datas.attachType

            let _disabledArr = []
            this.attachType.forEach(item => {
              if (item.disable) {
                _disabledArr.push(item.disable)
              }
            })
          }
        } else {
          this.$message.error(msg)
        }
      })
    },

    handleCancel () {
      this.previewVisible = false;
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange ({ fileList }) {
      this.fileList = fileList
    },

    handleChange1 ({ fileList }) {
      if (fileList[0]) {
        this.modalForm.file = 1 // 上传通过校验
      }
    },

    uploadBtnClkFn () {
      this.modalVisible = true
      this.$nextTick(() => {
        this.$refs['uploadModalDom'].clearValidate();
        this.$refs['uploadModalDom'].resetFields();
      })
    },

    modalHandleOk () {
      this.$refs.uploadModalDom.validate(valid => {
        if (valid) {
          this.confirmLoading = true;

          let params = {
            userId: this.$Storage.get('employDetail_userId'),
            attachType: this.modalForm.type,
            url: this.imgOssPath
          }
          attachmentAddOrUpdateflowersApi(params).then(res => {
            this.modalVisible = false
            this.confirmLoading = false

            let { code, msg } = res.data
            if (code == 200) {
              this.$message.success(msg)
              this.getData()
            } else {
              this.$message.error(msg)
            }
          })
        } else {
          return false;
        }
      });
    },

    modalHandleCancel () {
      this.modalVisible = false;
    },

    selectOnchange (value) {
      this.modalForm.type = value
    },

    uploadHandleChange (e) {
      let fileType = e.file.name

      fileType = fileType.substring(fileType.lastIndexOf('.'))

      if (/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(fileType)) {
        upLoadAliyun(e).then(res => {
          if (res.filePath) {
            this.imgOssPath = res.filePath
            this.$message.success('上传成功！')
          } else {
            this.$message.error('上传失败！')
          }

        })
      } else {
        this.$message.error('文件类型错误！')
        this.$refs.uploadDom.clearFiles()
      }
    },

    removeFn (file) {
      attachmentDelByIdApi(file.uid).then(res => {
        let { code, msg } = res.data
        if (code === 200) {
          this.$message.success(msg)
          // 更新上传类型select-disable
          this.getData()
        } else {
          this.$message.error(msg)
        }
      })
    }
  }
};
</script>

<style scoped lang="less">
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.img_upload_div {
  /deep/ .ant-upload-list-item-info {
    overflow: visible;
  }

  /deep/ .ant-upload-list-item-name.ant-upload-list-item-name-icon-count-1 {
    display: block;
    position: absolute;
    bottom: -35px;
    color: #595959;
  }
}
</style>